/**
 * 表格表单数据统一处理仓库
 */
import { ref, toRaw } from 'vue';
import request from '/@/utils/request';
import { ElMessage, type UploadFile } from 'element-plus';

const tableGridCatch: any = {};

export const setAPIConfig = (tableGridId: string, apiConfig: any) => {
    tableGridCatch[tableGridId] = initTableGridObj(apiConfig);
};

export const getTableGridObjById = (tableGridId: string) => {
    return tableGridCatch[tableGridId];
};

function initTableGridObj(apiConfig: any) {
    const API_CONFIG: any = Object.assign({}, apiConfig);
    
    const tableData = ref<any[]>();
    const paginationConfig = ref({
        pageNo: 1,
        pageSize: 20,
        total: 0
    });

    const dealDataFunction = {
        getTableData: (otherConfig: any = {}) => {
            // TODO: 接入数据获取接口
            request({
                url: API_CONFIG.tableDataApi,
                method: 'post',
                data: Object.assign({}, toRaw(paginationConfig.value), otherConfig)
            })
                .then((res: any) => {
                    tableData.value = res.data.list;
                    paginationConfig.value.total = res.data.total;
                })
                .catch(() => {
                    ElMessage.error('数据获取接口错误，请联系管理员！！！');
                    throw new Error('数据获取接口错误：' + API_CONFIG.tableDataApi);
                });
            tableData.value = [
                {
                    id: 1,
                    number: 10,
                    float: 10.21,
                    integer: 1000,
                    name: '测试1',
                    typeNumber: 100,
                    switch: false,
                    select: 'shenzhen',
                    select_DESC: '深圳',
                    checkboxGroup: ['shenzhen', 'chengdu'],
                    checkboxGroup_DESC: '深圳, 成都',
                    radioGroup: 'shenzhen',
                    radioGroup_DESC: '深圳',
                    color: '#409EFF',
                    datePicker: '2024-10-10',
                    dateTimePicker: '2024-10-18 12:00:00',
                    default: '测试默认赋值',
                    imgList: [
                        {
                            name: '3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
                        },
                        {
                            name: '19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
                        },
                        {
                            name: 'e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg'
                        },
                        {
                            name: 'e27858e973f5d7d3904835f46abbdjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
                        },
                        {
                            name: 'c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'
                        },
                        {
                            name: 'bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
                        },
                        {
                            name: '6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        }
                    ],
                    file: [
                        {
                            name: '测试.docx',
                            url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
                        },
                        {
                            name: '测试.xls',
                            url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
                        },
                        {
                            name: '测试.doc',
                            url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg'
                        },
                        {
                            name: '测试.pdf',
                            url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
                        },
                        {
                            name: '测试.txt',
                            url: 'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'
                        },
                        {
                            name: '测试.jpeg',
                            url: 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
                        },
                        {
                            name: '测试.jpg',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        },
                        {
                            name: '测试.png',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        }
                    ],
                    imgList1: [
                        {
                            name: '3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
                        },
                        {
                            name: '19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
                        },
                        {
                            name: 'e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg'
                        },
                        {
                            name: 'e27858e973f5d7d3904835f46abbdjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
                        },
                        {
                            name: 'c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'
                        },
                        {
                            name: 'bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
                        },
                        {
                            name: '6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        }
                    ],
                    file1: [
                        {
                            name: '测试.docx',
                            url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
                        },
                        {
                            name: '测试.xls',
                            url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
                        },
                        {
                            name: '测试.doc',
                            url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg'
                        },
                        {
                            name: '测试.pdf',
                            url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
                        },
                        {
                            name: '测试.txt',
                            url: 'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'
                        },
                        {
                            name: '测试.jpeg',
                            url: 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
                        },
                        {
                            name: '测试.jpg',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        },
                        {
                            name: '测试.png',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        }
                    ]
                },
                {
                    id: 2,
                    number: 20,
                    float: 10.21,
                    integer: 2000,
                    name: '测试2',
                    typeNumber: 200,
                    switch: true,
                    select: 'shenzhen',
                    select_DESC: '深圳',
                    checkboxGroup: ['shenzhen', 'chengdu'],
                    checkboxGroup_DESC: '深圳, 成都',
                    color: '#A6FF40',
                    datePicker: '2024-10-10',
                    dateTimePicker: '2024-10-18 12:00:00',
                    imgList: [
                        {
                            name: '3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
                        },
                        {
                            name: '19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
                        },
                        {
                            name: 'e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg'
                        },
                        {
                            name: 'e27858e973f5d7d3904835f46abbdjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
                        },
                        {
                            name: 'c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'
                        },
                        {
                            name: 'bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
                        },
                        {
                            name: '6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
                            url: 'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
                        }
                    ]
                },
                {
                    id: 3,
                    number: 30,
                    float: 10.21,
                    integer: 3000,
                    name: '测试3',
                    typeNumber: 300,
                    switch: false,
                    select: 'shenzhen',
                    select_DESC: '深圳',
                    checkboxGroup: ['shenzhen', 'chengdu'],
                    checkboxGroup_DESC: '深圳, 成都',
                    color: '#AE6540',
                    datePicker: '2024-10-10',
                    dateTimePicker: '2024-10-18 12:00:00'
                }
            ];
            paginationConfig.value.total = tableData.value.length;
        },
        addRow: async (data: any) => {
            const UpdateData: any = JSON.parse(JSON.stringify(data));
            for (const item of API_CONFIG.attachmentFields) {
                const fileUploadedResArr: Array<any> = [];
                if (data[item.fieldCode]) {
                    UpdateData[item.fieldCode] = [];
                    for (const ele of data[item.fieldCode]) {
                        fileUploadedResArr.push(await dealDataFunction.uploadFile(ele));
                    }
                    UpdateData[item.fieldCode] = fileUploadedResArr;
                }
            }
            API_CONFIG.numberFields.forEach((item: fieldConfig) => {
                UpdateData[item.fieldCode] = Number(UpdateData[item.fieldCode]);
            });
            try {
                const res: any = await request({
                    url: API_CONFIG.addFunctionApi,
                    method: 'post',
                    data: UpdateData
                });
                if (res.code === 200) {
                    dealDataFunction.getTableData();
                } else {
                    ElMessage.error('新增接口参数错误，请联系管理员！！！');
                    throw new Error('新增接口参数错误：' + API_CONFIG.addFunctionApi);
                }
                return res;
            } catch (error) {
                ElMessage.error('新增接口错误，请联系管理员！！！');
                throw new Error('新增接口错误：' + API_CONFIG.addFunctionApi);
            }
        },
        // data里边包含了数据记录的Id
        editRow: async (data: any) => {
            const UpdateData: any = JSON.parse(JSON.stringify(data));
            for (const item of API_CONFIG.attachmentFields) {
                const fileUploadedResArr: Array<any> = [];
                if (data[item.fieldCode]) {
                    UpdateData[item.fieldCode] = [];
                    for (const ele of data[item.fieldCode]) {
                        if (ele.status === 'ready') {
                            fileUploadedResArr.push(await dealDataFunction.uploadFile(ele));
                        }
                        if (ele.status === 'success') {
                            UpdateData[item.fieldCode].push(JSON.parse(JSON.stringify(ele)));
                        }
                    }
                    UpdateData[item.fieldCode].push(...fileUploadedResArr);
                }
            }
            API_CONFIG.numberFields.forEach((item: fieldConfig) => {
                UpdateData[item.fieldCode] = Number(UpdateData[item.fieldCode]);
            });
            try {
                const res: any = await request({
                    url: API_CONFIG.editFunctionApi,
                    method: 'post',
                    data: UpdateData
                });
                if (res.code === 200) {
                    dealDataFunction.getTableData();
                } else {
                    ElMessage.error('接口参数错误，请联系管理员！！！');
                    throw new Error('接口参数错误：' + API_CONFIG.editFunctionApi);
                }
                return res;
            } catch (error) {
                ElMessage.error('编辑接口错误，请联系管理员！！！');
                throw new Error('编辑接口错误：' + API_CONFIG.editFunctionApi);
            }
        },
        deleteRows: async (ids: string) => {
            try {
                const res: any = await request({
                    url: API_CONFIG.deleteFunctionApi,
                    method: 'post',
                    data: { ids }
                });
                if (res.code === 200) {
                    dealDataFunction.getTableData();
                } else {
                    ElMessage.error('接口参数错误，请联系管理员！！！');
                    throw new Error('接口参数错误：' + API_CONFIG.deleteFunctionApi);
                }
                return res;
            } catch (error) {
                ElMessage.error('删除接口错误，请联系管理员！！！');
                throw new Error('删除接口错误：' + API_CONFIG.deleteFunctionApi);
            }
        },
        handleSizeChange: (pageSize: number) => {
            paginationConfig.value.pageSize = pageSize;
            dealDataFunction.getTableData();
        },
        handleCurrentChange: (pageNo: number) => {
            paginationConfig.value.pageNo = pageNo;
            dealDataFunction.getTableData();
        },
        searchTableData: (searchParams: any) => {
            paginationConfig.value.pageNo = 1;
            dealDataFunction.getTableData(searchParams);
        },
        uploadFile: async (fileObj: UploadFile) => {
            let formData = new FormData();
            formData.append('name', fileObj.name);
            formData.append('file', fileObj.raw as File);
            try {
                const res: any = await request({
                    url: API_CONFIG.uploadFileApi,
                    method: 'post',
                    data: formData
                });
                if (res.code === 200) {
                    return res.data;
                } else {
                    ElMessage.error('接口参数错误，请联系管理员！！！');
                    throw new Error('接口参数错误：' + API_CONFIG.uploadFileApi);
                }
            } catch (error) {
                ElMessage.error('文件上传接口错误，请联系管理员！！！');
                throw new Error('文件上传接口错误：' + API_CONFIG.uploadFileApi);
            }
        },
        deleteFile: async (fileObjId: Number) => {
            try {
                const res: any = await request({
                    url: API_CONFIG.deleteFileApi,
                    method: 'post',
                    data: {
                        id: fileObjId
                    }
                });
                if (res.code === 200) {
                    return res.data;
                } else {
                    ElMessage.error('文件删除接口参数错误，请联系管理员！！！');
                    throw new Error('文件删除接口参数错误：' + API_CONFIG.deleteFileApi);
                }
            } catch (error) {
                ElMessage.error('文件删除接口错误，请联系管理员！！！');
                throw new Error('文件删除接口错误：' + API_CONFIG.deleteFileApi);
            }
        }
    };

    return {
        tableData,
        paginationConfig,
        ...dealDataFunction
    }
}
